package helloworld.admin.service.news;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import helloworld.dao.NewsDao;
import helloworld.dao.DAOException;
import helloworld.dao.DAOFactory;
import helloworld.example.exception.ErrorLevel;
import helloworld.exception.DuplicateNewsException;

import helloworld.admin.bean.*;

/**
 * In real projects, NewsControllerService object is often implemented as Session EJB.
 * It represents a Business Service and is Session Facade pattern (Core J2EE Patterns) 
 * 
 * @author TUYEN-DM
 * @version $Revision:   $ $Date:2009/05/25   $
 */
public class NewsControllerService {

	public NewsAdminBean getNewsDetail(String newsName) throws NewsServiceException
	{
		NewsAdminBean news = null;
		try{
			DAOFactory factory = DAOFactory.getDAOFactory(DAOFactory.MS_ACCESS);
			NewsDao dao = factory.getNewsDAO();
			news = dao.fetchDetail(newsName);
			
		}catch (DAOException de)
		{
			if (! de.isLogged())
			{
				Log log = LogFactory.getLog("NewsFetchService");
				de.log(log);
			}
			throw new NewsServiceException(de.getUserMessageKey(), 
									de.getValueReplacementArray(),
									de.getUniqueID(), 
									ErrorLevel.ERROR);
		}
		
		return news;
	}
	
	public int createNews(NewsAdminBean news) throws NewsServiceException, DuplicateNewsException{
		try{			
			DAOFactory factory = DAOFactory.getDAOFactory(DAOFactory.MS_ACCESS);
			NewsDao dao = factory.getNewsDAO();
			return dao.create(news);
		}catch (DAOException de) {
			// TODO: handle exception
			if(!de.isLogged()){
				Log log = LogFactory.getLog("NewsInsertService");
				de.log(log);
			}
			throw new NewsServiceException(de.getUserMessageKey(),de.getValueReplacementArray(),
												de.getUniqueID(),ErrorLevel.ERROR);
		}
	}
	
	public void updateNews(NewsAdminBean news)throws NewsServiceException,DuplicateNewsException{
		try{
			DAOFactory factory = DAOFactory.getDAOFactory(DAOFactory.MS_ACCESS);
			NewsDao dao = factory.getNewsDAO();
			dao.update(news);
		}catch (DAOException de) {
			// TODO: handle exception
			if(!de.isLogged()){
				Log log = LogFactory.getLog("NewsUpdateService");
				de.log(log);
			}
			throw new NewsServiceException(de.getUserMessageKey(),de.getValueReplacementArray(),
												de.getUniqueID(),ErrorLevel.ERROR);
		}
	}
	
	public void deleteNews(int id) throws NewsServiceException{
		try{
			
			DAOFactory factory = DAOFactory.getDAOFactory(DAOFactory.MS_ACCESS);
			NewsDao dao = factory.getNewsDAO();
			dao.delete(id);
		}catch (DAOException de) {
			// TODO: handle exception
			if(!de.isLogged()){
				Log log = LogFactory.getLog("NewsDeleteService");
				de.log(log);
			}
			throw new NewsServiceException(de.getUserMessageKey(),de.getValueReplacementArray(),
												de.getUniqueID(),ErrorLevel.ERROR);
		}
	}
}
